package com.henzil.siji;

import com.henzil.siji.bean.VehiclesInfo;
import com.henzil.siji.data.DriverContentProvider;
import com.henzil.siji.util.Global;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;

public class CarImagesPickerActivity extends Activity{

	GridView gridView;
	
	private CarImagesPickerAdapter adapter;
	
	ImageView selectImage; 
	
	VehiclesInfo vehiclesInfo = new VehiclesInfo();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.car_image);
		initView();
		setVehiclesInfo();
		
	}
	
	private void initView(){
		selectImage = (ImageView) findViewById(R.id.select_image);
		
		gridView = (GridView) findViewById(R.id.gridView);
		adapter = new CarImagesPickerAdapter(this);
		gridView.setAdapter(adapter);
		adapter.refresh();
		
		findViewById(R.id.but_ok).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ContentValues contentValues = new ContentValues();
				contentValues.put(DriverContentProvider.IMAGE_ID, vehiclesInfo.getImageId());
				
				String[] strs = {String.valueOf(vehiclesInfo.getId())};
				getContentResolver().update
					(DriverContentProvider.CONTENT_URI_UPDATE_VEHICLESINFO, contentValues, DriverContentProvider._ID+"=?", strs);
				
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putInt("vehiclesInfo_id", vehiclesInfo.getId());
				bundle.putInt("imageId", vehiclesInfo.getImageId());
				
				
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		
		findViewById(R.id.but_cancel).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}
	
	private void setVehiclesInfo(){
		Bundle bundle = getIntent().getExtras();
		if(bundle != null){
			Log.v(Global.TAG, ""+bundle);
			Log.v(Global.TAG, ""+bundle.getInt("vehiclesInfo_id"));
			vehiclesInfo.setId(bundle.getInt("vehiclesInfo_id"));
//			bundle.getString("_id");
//			bundle.getInt("_id");
			vehiclesInfo.setImageId(bundle.getInt("imageId"));
			selectImage.setImageResource(vehiclesInfo.getImageId()==-1 ? R.drawable.icon_addcar_placeholder : Global.getImageIdList().get(vehiclesInfo.getImageId()));
		}
	}
}
